from tornado.web import RequestHandler
from functools import wraps
from datetime import datetime
from .JsonResponse import FuncErrorResponse, ErrorResponse
import json
from Server.GlobalConfig import Driver


def record_http_request(func):
    @wraps(func)
    def record(self, *args, **kwargs):
        request_time = str(datetime.now())
        http_request = dict(
            request_time=request_time,
            method=self.request.method,
            url=self.request.uri,
            request_params=self.request.body,
            response_code=self.get_status(),
        )
        print(http_request, flush=True)
        response = None
        try:
            prefix = self.request.uri.split('/api/v1/')[-1].split('/')[0]
            func_name = Driver.function_support(prefix, args)
            if func_name is None:
                self.write(ErrorResponse('Operate not support:' + str(args)).to_str())
                return
            args_list = Driver.args_define(func_name)
            if len(args_list) > 0:
                data = json.loads(self.request.body)
                if Driver.args_support(func_name, dict(data).keys()) is False:
                    self.write(ErrorResponse('Operate should contains {} args'.format(str(args_list))).to_str())
                    return
            response = func(self, *args, **kwargs)
        except Exception as e:
            self.write(FuncErrorResponse(str(e)).to_str())
        finally:
            return response

    return record


class BaseHandler(RequestHandler):
    """解决JS跨域请求问题"""

    def set_default_headers(self):
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_header('Access-Control-Allow-Methods', 'POST, GET')
        self.set_header('Access-Control-Max-Age', 1000)
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Content-type', 'application/json')

    def options(self, *args, **kwargs):
        self.set_header("Access-Control-Allow-Origin", "*")
        self.write("ok")
